﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using Microsoft.Web.Mvc;
using JqueryMvc.Attributes;

namespace JqueryMvc.Mvc
{
    public class DefaultViewViewEngine: IViewEngine
    {
		public DefaultViewViewEngine()
        {
        }

        public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
			return new ViewEngineResult(new string[] { }); //partials cannot have a defaultview, can't think of a reason for this
		}

        public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
			if (controllerContext != null && controllerContext.Controller != null)
			{
                controllerContext.HttpContext.Items["_ORIGINGAL_VIEWNAME"] = viewName;
                if (!viewName.StartsWith("_"))
                {
                    object[] attribs = controllerContext.Controller.GetType().GetCustomAttributes(typeof(DefaultViewAttribute), true);
                    if (attribs != null && attribs.Length > 0)
                    {
                        foreach (DefaultViewAttribute attrib in attribs)
                        {
                            if (attrib.ViewName != viewName)
                            {
                                ViewEngineResult result = ViewEngines.Engines.FindView(controllerContext, attrib.ViewName, masterName);
                                if (result != null && result.View != null)
                                    return result;
                            }
                        }
                    }
                }
                else if (controllerContext.HttpContext.Request.IsJqAjaxRequest())
                {
                    ViewEngineResult result = ViewEngines.Engines.FindView(controllerContext, viewName.Substring(1), masterName);
                    if (result != null && result.View != null)
                        return result;
                }
			}

			return new ViewEngineResult(new string[] {});
		}

        public void ReleaseView(ControllerContext controllerContext, IView view)
        {
            if (view != null && view is IDisposable)
                (view as IDisposable).Dispose();
        }
    }
}
